import { getCampusSelector } from '@/api/campus/campus'
import request from '@/utils/request'
export default {
  components: {},
  props: [],
  data() {
    const validatePlan = (rule, value, callback) => {
      if (value === '' || value.length < 1) {
        callback(new Error('请上传开业计划表'))
      } else {
        callback()
      }
    }
    const validateSurvey = (rule, value, callback) => {
      if (value === '' || value.length < 1) {
        callback(new Error('请上传校区市调表'))
      } else {
        callback()
      }
    }
    const validateCalendar = (rule, value, callback) => {
      if (value === '' || value.length < 1) {
        callback(new Error('请上传开业行事历'))
      } else {
        callback()
      }
    }
    const validateEnvironment = (rule, value, callback) => {
      if (value === '' || value.length < 1) {
        callback(new Error('校区门头、前台、主要功能区、校内环创'))
      } else {
        callback()
      }
    }
    return {
      setting: {},
      eventType: '',
      dataForm: {
        id: '',
        brand: undefined,
        campusId: undefined,
        type: undefined,
        openDate: undefined,
        tutorialDate: [],
        counselor: undefined,
        plan: [],
        survey: [],
        calendar: [],
        degreeCount: undefined,
        regular: undefined,
        lead: undefined,
        price: [],
        summarize: undefined,
        bedNum: undefined,
        environment: [],
        daySchedule: [],
        team: [],
        activity: []
      },
      rules: {
        brand: [
          {
            required: true,
            message: '请选择校区品牌',
            trigger: 'change'
          }
        ],
        campusId: [
          {
            required: true,
            message: '请选择辅导校区',
            trigger: 'change'
          }
        ],
        openDate: [
          {
            required: true,
            message: '请输入开业日期',
            trigger: 'change'
          }
        ],
        tutorialDate: [
          {
            required: true,
            message: '请选择辅导开始日期',
            trigger: 'change'
          }
        ],
        counselor: [
          {
            required: true,
            message: '请输入辅导师',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择开业类型',
            trigger: 'change'
          }
        ],
        plan: [{ required: true, validator: validatePlan, trigger: 'change' }],
        survey: [{ required: true, validator: validateSurvey, trigger: 'change' }],
        calendar: [{ required: true, validator: validateCalendar, trigger: 'change' }],
        environment: [{ required: true, validator: validateEnvironment, trigger: 'blur' }],
        summarize: [
          {
            required: true,
            message: '请输入校区开业总结',
            trigger: 'blur'
          }
        ]
      },
      campusOptions: [],
      campusLoading: false,
      brandOptions: [],
      typeOptions: [{ fullName: '新校开业', id: '1' }, { fullName: '多校自主开业', id: '2' }]
    }
  },
  computed: {},
  watch: {
    'dataForm.plan': {
      handler: function(newVal) {
        if (newVal.length) {
          this.$refs['elForm'].clearValidate('plan')
        }
      },
      deep: true,
      immediate: true
    },
    'dataForm.survey': {
      handler: function(newVal) {
        if (newVal.length) {
          this.$refs['elForm'].clearValidate('survey')
        }
      },
      deep: true,
      immediate: true
    },
    'dataForm.calendar': {
      handler: function(newVal) {
        if (newVal.length) {
          this.$refs['elForm'].clearValidate('calendar')
        }
      },
      deep: true,
      immediate: true
    },
    'dataForm.environment': {
      handler: function(newVal) {
        if (newVal.length) {
          this.$refs['elForm'].clearValidate('environment')
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  mounted() {},
  methods: {
    goBack() {
      this.$emit('refresh')
    },
    init(data) {
      this.setting = data
      this.dataForm.id = data.id || ''
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (this.dataForm.id) {
          request({
            url: '/api/campus/open/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data
            this.handleChangeBrand(this.dataForm.brand)
            if (!this.dataForm.plan) this.dataForm.plan = []
            if (!this.dataForm.survey) this.dataForm.survey = []
            if (!this.dataForm.calendar) this.dataForm.calendar = []
            if (!this.dataForm.price) this.dataForm.price = []
            if (!this.dataForm.environment) this.dataForm.environment = []
            if (!this.dataForm.daySchedule) this.dataForm.daySchedule = []
            if (!this.dataForm.team) this.dataForm.team = []
            if (!this.dataForm.activity) this.dataForm.activity = []
          })
        }
      })
    },
    dataFormSubmit(eventType) {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (eventType === 'audit' || eventType === 'reject') {
            this.$emit('eventReciver', this.dataForm, eventType)
            return
          }
          this.dataForm.flowState = eventType === 'submit' ? 0 : 1
          this.eventType = eventType
          if (this.eventType === 'submit') {
            this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
              type: 'warning'
            })
              .then(() => {
                this.request()
              })
              .catch(() => {})
          } else {
            this.request()
          }
        }
      })
    },
    request() {
      const requestPromise = this.dataForm.id
        ? request({
            url: `/api/campus/open/${this.dataForm.id}`,
            method: 'put',
            data: this.dataForm
          })
        : request({
            url: `/api/campus/open`,
            method: 'post',
            data: this.dataForm
          })

      requestPromise
        .then(res => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.$emit('close', true)
            }
          })
        })
        .catch(error => {
          console.error('提交失败:', error)
          let errorMessage = '提交失败'

          // 处理不同类型的错误
          if (error && error.response) {
            // HTTP错误响应
            const responseData = error.response.data || {}
            errorMessage = responseData.message || responseData.msg || `请求失败 (${error.response.status})`
          } else if (error && error.message) {
            // JavaScript Error对象
            errorMessage = error.message
          } else if (typeof error === 'string') {
            // 字符串错误
            errorMessage = error
          } else if (error && typeof error === 'object') {
            // 其他对象类型错误
            errorMessage = JSON.stringify(error)
          }

          this.$message.error(errorMessage)
        })
        .finally(() => {})
    },
    async handleChangeBrand(val) {
      try {
        this.campusLoading = true
        const res = await getCampusSelector({ brand: val, fields: 'id,fullName' })
        const list = Array.isArray(res.data) ? res.data : []
        if (!this.dataForm.id) {
          this.campusOptions = list.filter(i => i.status != 'close' && i.status != 'expires')
        } else {
          this.campusOptions = list
        }
      } catch (err) {
        console.error('加载校区下拉选项失败:', err)
        this.$message.error('校区选项加载失败')
        this.campusOptions = []
      } finally {
        this.campusLoading = false
      }
    },
    loadCampusOptions() {
      this.handleChangeBrand(this.dataForm.brand)
    },
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return true
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.read
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return !item.write
    }
  }
}
